using System;
using System.Collections.Generic;
using Arcane.Source.TileMatch;
using Arcane.Source.TileMatch.Tile;
using Arcane.Source.Utils;
using Godot;

namespace Arcane.Source.Client;

public partial class TileCell : Node2D
{
    private float offset;
    private int _level;

    private Texture2D _texture;
    private float _size;
    private Tween _tween = null;

    public bool Animating => _tween?.IsRunning() == true;

    public TileCell(Vector2 position)
    {
        Position = position;
    }

    public override void _Draw()
    {
        var halfSize = 0.5f * _size;
        DrawTextureRect(_texture, new Rect2(-halfSize, -halfSize - offset, _size, _size), false);
    }

    public void Resize(float size)
    {
        _size = size.ToMaximumIntMul(18);
    }

    public void Sync(ITile tile, TileMatcher matcher)
    {
        Visible = true;
        StopTween();
        if (tile is RuneTile rune)
        {
            _level = rune.Level;
            _texture = matcher.GetElementTexture(rune.Element, rune.Level);
            if (rune.IsDroping(out var tick))
            {
                offset = matcher.CellSize * (1f - (float)tick / Rule.DROP_TICK);
            }
            QueueRedraw();
        }
        else
        {
            Visible = false;
        }
    }

    public void MoveTo(Vector2 position)
    {
        StopTween();

        _tween = CreateTween();
        _tween.TweenProperty(this, "position", position, 0.1);
    }

    public void InstantMoveTo(Vector2 position)
    {
        StopTween();

        Position = position;
    }

    public void HintTo(Vector2 pos)
    {
        if (_tween?.IsValid() == true) return;

        _tween = CreateTween();
        _tween.TweenProperty(this, "position", Position.Lerp(pos, 0.2f), 0.1);
        _tween.TweenProperty(this, "position", Position, 0.1);
        _tween.TweenProperty(this, "position", Position.Lerp(pos, 0.2f), 0.1);
        _tween.TweenProperty(this, "position", Position, 0.1);
    }

    private void StopTween()
    {
        if (_tween?.IsValid() == true)
        {
            _tween.Kill();
        }
    }
}